package com.ys.chatserver.tool;

import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.*;
import java.awt.geom.AffineTransform;
import java.awt.image.BufferedImage;
import java.awt.image.ColorModel;
import java.awt.image.WritableRaster;
import java.io.File;
import java.io.IOException;
import java.util.Hashtable;

public class ImgEqualScaleAndCutHelper {
    public ImgEqualScaleAndCutHelper() {
    }

    public static void saveImageAsJpg(String inFilePath, String outFilePath, int width, int hight) throws Exception {
        File file = new File(inFilePath);
        File saveFile = new File(outFilePath);
        Image src = Toolkit.getDefaultToolkit().getImage(file.getPath());
        BufferedImage srcImage = toBufferedImage(src);
        int w;
        int h;
        if (width > 0 || hight > 0) {
            w = srcImage.getWidth();
            h = srcImage.getHeight();
            if (w <= width || h <= hight) {
                String fileName = saveFile.getName();
                String formatName = fileName.substring(fileName.lastIndexOf(46) + 1);
                ImageIO.write(srcImage, formatName, saveFile);
                return;
            }

            srcImage = resize(srcImage, width, hight);
        }

        w = srcImage.getWidth();
        h = srcImage.getHeight();
        System.out.println("width=" + width + ", hight=" + hight + " -> w=" + w + ", h=" + h);
        if (w == width) {
            int x = 0;
            int y = h / 2 - hight / 2;
            saveSubImage(srcImage, new Rectangle(x, y, width, Math.min(hight, h)), saveFile);
        } else if (h == hight) {
            int x = w / 2 - width / 2;
            int y = 0;
            saveSubImage(srcImage, new Rectangle(x, y, Math.min(width, w), hight), saveFile);
        }
    }

    private static BufferedImage resize(BufferedImage source, int targetW, int targetH) {
        int type = source.getType();
        BufferedImage target = null;
        double sx = (double) targetW / (double) source.getWidth();
        double sy = (double) targetH / (double) source.getHeight();
        if (sx < sy) {
            sx = sy;
            targetW = (int) (sy * (double) source.getWidth());
        } else {
            sy = sx;
            targetH = (int) (sx * (double) source.getHeight());
        }

        if (type == 0) {
            ColorModel cm = source.getColorModel();
            WritableRaster raster = cm.createCompatibleWritableRaster(targetW, targetH);
            boolean alphaPremultiplied = cm.isAlphaPremultiplied();
            target = new BufferedImage(cm, raster, alphaPremultiplied, (Hashtable) null);
        } else {
            target = new BufferedImage(targetW, targetH, type);
        }

        Graphics2D g = target.createGraphics();
        g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC);
        g.drawRenderedImage(source, AffineTransform.getScaleInstance(sx, sy));
        g.dispose();
        return target;
    }

    private static void saveSubImage(BufferedImage image, Rectangle subImageBounds, File subImageFile) throws IOException {
        if (subImageBounds.x >= 0 && subImageBounds.y >= 0 && subImageBounds.width - subImageBounds.x <= image.getWidth() && subImageBounds.height - subImageBounds.y <= image.getHeight()) {
            BufferedImage subImage = image.getSubimage(subImageBounds.x, subImageBounds.y, subImageBounds.width, subImageBounds.height);
            String fileName = subImageFile.getName();
            String formatName = fileName.substring(fileName.lastIndexOf(46) + 1);
            ImageIO.write(subImage, formatName, subImageFile);
        } else {
            System.out.println("Bad   subimage   bounds");
        }
    }


    private static BufferedImage toBufferedImage(Image image) {
        if (image instanceof BufferedImage) {
            return (BufferedImage) image;
        }
        // This code ensures that all the pixels in the image are loaded
        image = new ImageIcon(image).getImage();
        BufferedImage bimage = null;
        GraphicsEnvironment ge = GraphicsEnvironment
                .getLocalGraphicsEnvironment();
        try {
            int transparency = Transparency.OPAQUE;
            GraphicsDevice gs = ge.getDefaultScreenDevice();
            GraphicsConfiguration gc = gs.getDefaultConfiguration();
            bimage = gc.createCompatibleImage(image.getWidth(null),
                    image.getHeight(null), transparency);
        } catch (HeadlessException e) {
            // The system does not have a screen
        }
        if (bimage == null) {
            // Create a buffered image using the default color model
            int type = BufferedImage.TYPE_INT_RGB;
            bimage = new BufferedImage(image.getWidth(null),
                    image.getHeight(null), type);
        }
        // Copy image to buffered image
        Graphics g = bimage.createGraphics();
        // Paint the image onto the buffered image
        g.drawImage(image, 0, 0, null);
        g.dispose();
        return bimage;
    }

    public static void main(String[] args) throws Exception {
        saveImageAsJpg("c:/emoji_95.png", "c:/th_emoji_95.png", 245, 245);
    }
}